﻿using System;
using System.Collections.Generic;
using System.Text;

namespace MyLibrary.ThreeLayer.Entity
{
    /// <summary>
    /// 字符串型字段的验证
    /// </summary>
    [AttributeUsage(AttributeTargets.Property)]
    public class StringFieldAttribute : ValidateAttribute,IValidateAttribute<String>
    {
        int _length = Int32.MaxValue;
        string _default = String.Empty;
        /// <summary>
        /// 字符串的长度
        /// </summary>
        public int Length
        {
            get { return _length; }
            set { _length = value; }
        }

        /// <summary>
        /// 默认值
        /// </summary>
        public string Default
        {
            get
            {
                return this._default;
            }
            set
            {
                this._default = value;
            }
        }

        //public StringFieldAttribute(int length) : this(false, String.Empty, length) { }
        //public StringFieldAttribute(bool allowEmpty, int length) : this(allowEmpty, String.Empty, length) { }
        //public StringFieldAttribute() : this(true, String.Empty, Int32.MaxValue) { }
        //public StringFieldAttribute(bool allowEmpty, string defaultValue, int length) : base(allowEmpty)
        //{
        //    this._default = defaultValue;
        //    this._length = length;
        //}

        public StringFieldAttribute() { }

        bool IValidateAttribute<string>.IsValidate(string value)
        {
            if (!base.AllowEmpty)
            {
                if (!base.ValidateAllowEmpty(value))
                    throw new ArgumentException("value", "指定的域值不能为空");
            }
            //TODO:Other Validate
            if (this._length != Int32.MaxValue)
            {
                if (value.Length > this._length)
                    throw new ArgumentException("value", "指定域的值的长度超过范围");
            }
            return true;
        }
    }
}
